<template>
  <view class="schedule-list-container">
    <!-- 顶部Tab切换 -->
    <view class="schedule-tabs">
      <view v-for="(tab, idx) in tabs" :key="tab" :class="['tab', { active: activeTab === idx }]"
        @click="tabClick(tab, idx)">
        {{ tab.name }}
      </view>
    </view>
    <!-- 赛程列表 -->
    <scroll-view 
      class="schedule-list" 
      scroll-y 
      @scrolltolower="onLoadMore"
      :style="{ height: '600rpx' }"
    >
      <view v-for="(item, idx) in scheduleList" :key="idx" class="schedule-item" @click="handleDetail(item)">
        <view class="schedule-time">{{ item.start_time }} </view>
        <view class="schedule-group">{{ item.group_name }}-{{ item.item_name }}</view>
        <image class="arrow-icon" :src="imgUrl + 'arrow-right.png'" />
      </view>
      
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-more">
        <text>加载中...</text>
      </view>
      
      <!-- 没有更多数据提示 -->
      <view v-if="!hasMore && scheduleList.length > 0" class="no-more">
        <text>没有更多数据了</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
  import { ref, computed, watch, nextTick } from 'vue';
  import { imgUrl } from '@/utils/config'
  import { onShow } from '@dcloudio/uni-app';
  import { useRequest } from '@/api';
  import { formatTime } from '@/utils/dateUtils.js'
  const props = defineProps({
    mainId: {
      type: Number,
      required: true,
    },
  });
  
  const { API_INDEX_LISTCOURSE_POST } = useRequest();
  
  // const tabs = ['径赛赛程', '径赛赛果', '田赛赛程'];
  //type:类别:径赛 track, 田赛 field
  //result : 赛程 begin 赛果 end
  const tabs = ref([
    {
      name: '径赛赛程',
      type: 'track',
      result:'begin'
    },
    {
      name: '径赛赛果',
      type: 'track',
      result:'end'
    },
    {
      name: '田赛赛程',
      type: 'field',
      result:'begin'
    },
    {
      name: '田赛赛果',
      type: 'field',
      result:'end'
    }
  ]);
  const activeTab = ref(0);
  const scheduleList = ref([]);
  const type = ref('track');
  const result = ref('begin');
  
  // 分页相关状态
  const currentPage = ref(1);
  const pageSize = ref(10);
  const loading = ref(false);
  const hasMore = ref(true);
  
  // 将函数定义移到 watch 之前
  const getScheduleList = async (mainId, type, result, isLoadMore = false) => {
    if (!mainId) {
      return;
    }
    
    // 如果不是加载更多，重置分页状态
    if (!isLoadMore) {
      currentPage.value = 1;
      scheduleList.value = [];
      hasMore.value = true;
    }
    
    // 如果没有更多数据，直接返回
    if (isLoadMore && !hasMore.value) {
      return;
    }
    
    loading.value = true;
    
    let params = {
      page: currentPage.value,
      page_size: pageSize.value,
      id: mainId,
      type: type,
      result: result
    }
    
    try {
      const res = await API_INDEX_LISTCOURSE_POST(params)
      console.log('getScheduleList', res)

      if (res.code === 1) {
        const newData = res.data.data || [];
        
        if (isLoadMore) {
          // 加载更多：追加数据
          scheduleList.value = [...scheduleList.value, ...newData];
        } else {
          // 首次加载或切换tab：替换数据
          scheduleList.value = newData;
        }
        
        // 判断是否还有更多数据
        hasMore.value = newData.length === pageSize.value;
        
        console.log('赛程数据:', scheduleList.value);
        console.log('当前页:', currentPage.value, '是否有更多:', hasMore.value);
      } else {
        uni.showToast({ title: res.msg, icon: 'none' })
      }
    } catch (error) {
      uni.showToast({ title: error.message, icon: 'none' })
    } finally {
      loading.value = false;
    }
  }

  // 加载更多数据
  const onLoadMore = async () => {
    if (loading.value || !hasMore.value) {
      return;
    }
    
    currentPage.value += 1;
    await getScheduleList(props.mainId, type.value, result.value, true);
  }

  // 监听 mainId 数据变化
  watch(() => props.mainId, async (newMainId) => {
    if (newMainId && newMainId > 0) {
      console.log('mainId data updated:', newMainId);
      activeTab.value = 0;
      // 在这里处理数据更新后的逻辑
      await getScheduleList(newMainId, 'track', 'begin'); // 默认显示径赛赛程
      // 等待 DOM 更新完成
      await nextTick();
    }
  }, { immediate: true, deep: true });

  // const filteredList = computed(() => {
  //   // 这里可以根据activeTab过滤不同类型的赛程
  //   // 示例：假设所有数据都展示
  //   return scheduleList.value;
  // });

  const handleDetail = (item) => {
    console.log('mainId', props.mainId);
    
    console.log('handleDetail', item);
    uni.navigateTo({
      url: `/pages/ScheduleDetail/index?event_id=${item.event_id}&item_id=${item.item_id}&type=${type.value}&result=${result.value}&competition_time=${item.competition_time}&item_name=${item.item_name}&type=${type.value}&result=${result.value}&start_time=${item.start_time}&end_time=${item.end_time}`
    })
    // uni.showToast({
    //   title: `查看${item.group}详情`,
    //   icon: 'none'
    // });
  };

  const tabClick = (tab, index) => {
    activeTab.value = index;
    type.value = tab.type;
    result.value = tab.result;
    // 切换tab时重置分页并重新加载
    getScheduleList(props.mainId, tab.type, tab.result);
  }
</script>

<style lang="scss" scoped>
  .schedule-list-container {
    background: #fff;
    border-radius: 16rpx;
    padding: 24rpx 5rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  }

  .schedule-tabs {
    display: flex;
    margin-bottom: 24rpx;

    .tab {
      padding: 12rpx 18rpx;
      font-size: 28rpx;
      color: #888;
      background: #f5f5f5;
      border-radius: 12rpx 12rpx 0 0;
      margin-right: 16rpx;
      font-weight: 500;

      &.active {
        background: #2979ff;
        color: #fff;
      }
    }
  }

  .schedule-list {
    .schedule-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .schedule-time {
        font-size: 26rpx;
        color: #333;
        flex: 1.5;
      }

      .schedule-group {
        font-size: 26rpx;
        color: #2979ff;
        flex: 1;
        text-align: right;
        margin-right: 20rpx;
      }

      .arrow-icon {
        width: 32rpx;
        height: 32rpx;
      }
    }
    
     /* 加载更多样式 */
    .loading-more, .no-more {
      text-align: center;
      padding: 30rpx 0;
      color: #999;
      font-size: 24rpx;
    }
    
    .loading-more {
      color: #2979ff;
    }
  }
</style>